import { config } from "../config/index";
import fs from "fs";
import path from "path";

export class utils {

    /**
     * 统一设置网站浏览器的 title 标题内容
     * @param title 
     */
    public static titleName(title:string):string {
        return `${title}${config.title}`
    }
    
    public static parseQueryString (url) {
        var reg_url = /^[^\?]+\?([\w\W]+)$/,
          reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
          arr_url = reg_url.exec(url),
          ret = {};
        if (arr_url && arr_url[1]) {
            var str_para = arr_url[1], result;
            while ((result = reg_para.exec(str_para)) != null) {
                ret[result[1]] = result[2];
            }
        }
        return ret;
    }
    
    /**
     * 获取文件的后缀
     * @param name 文件名
     */
    public getUploadFileExt(name:string): string {
        let ext = name.split('.');
        return ext[ext.length - 1];
    }

    /**
     * 判断文件夹是否存在 如果不存在则创建文件夹
     * @param dir 文件路径
     */
    public checkDirExist(dir:string): void {
        dir = path.join(__dirname,`${config.uploadPath}${dir}`)
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
        }
    }

    /**
     * 时间戳+随机字符生成图片名称
     * 例如：20192323434235325.jpg
     * @param ext
     */
    public getUploadFileName(ext:string): string {
        // @ts-ignore
        return `${Date.now()}${Number.parseInt(Math.random() * 10000)}.${ext}`;
    }
    
    /**
     * 获取上传文件夹名称，按照时间创建
     */
    public getUploadDirName(): string {
        const date = new Date();
        // @ts-ignore
        let month = Number.parseInt( date.getMonth() ) + 1;
        month = month.toString().length > 1 ? month : `0${month}`;
        const dir = `${date.getFullYear()}${month}${date.getDate()}`;
        
        this.checkDirExist(dir);
        
        return dir;
    }
    
    /**
     * 上传文件，主要是讲图片的buffer写入到指定文件夹中存放
     * @param file 文件对象
     * @constructor
     */
    public UpLoadFileImg(file:any):String {
        // 文件后缀名
        const FileExt = this.getUploadFileExt(file.originalname);
        // 文件夹名称 20190530
        const UploadDirName = this.getUploadDirName();
        // 文件名称 20194324232.jpg
        const UploadFileName = this.getUploadFileName(FileExt);
        
        const CompletePath = `${path.join(__dirname,`${config.uploadPath}${UploadDirName}`)}/${UploadFileName}`
        fs.writeFile(CompletePath, file.buffer, (err) => {
            if(err) {
              console.log(err)
            }
        });
        
        return `http://geekhelp.cn/upload/${UploadDirName}/${UploadFileName}`
    
    }
}